<template>
  <div class="schedule-management">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">我的排班</span>
        </div>
      </template>

      <el-table
        :data="schedules"
        style="width: 100%"
        v-loading="loading"
        class="feedback-table"
        :border="true"
        :stripe="true"
        :height="tableHeight"
      >
        <el-table-column prop="day_of_week" label="星期" width="120">
          <template #default="scope">
            {{ getDayOfWeek(scope.row.day_of_week) }}
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="150">
          <template #default="scope">
            {{ formatTime(scope.row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="150">
          <template #default="scope">
            {{ formatTime(scope.row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'" size="small">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" @click="viewScheduleDetail(scope.row)" class="operation-button">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 排班详情对话框 -->
    <el-dialog
      title="排班详情"
      v-model="detailDialogVisible"
      width="600px"
      class="detail-dialog"
    >
      <el-form
        :model="selectedSchedule"
        label-width="120px"
        label-position="left"
        :inline="false"
      >
        <el-form-item label="星期：">
          <el-input v-model="selectedSchedule.day_text" readonly />
        </el-form-item>

        <el-form-item label="开始时间：">
          <el-input :value="formatTime(selectedSchedule.start_time)" readonly />
        </el-form-item>

        <el-form-item label="结束时间：">
          <el-input :value="formatTime(selectedSchedule.end_time)" readonly />
        </el-form-item>

        <el-form-item label="状态：">
          <el-tag :type="selectedSchedule.is_active ? 'success' : 'danger'">
            {{ selectedSchedule.is_active ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import requestUtil from '@/util/request.js'

// 数据相关
const schedules = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)

// 详情对话框数据
const selectedSchedule = ref({})

// 星期选项
const weekdays = [
  { value: '1', label: '星期一' },
  { value: '2', label: '星期二' },
  { value: '3', label: '星期三' },
  { value: '4', label: '星期四' },
  { value: '5', label: '星期五' },
  { value: '6', label: '星期六' },
  { value: '7', label: '星期日' }
]

// 将秒数转换为 HH:mm:ss 格式
const secondsToTimeString = (seconds) => {
  // 处理浮点数
  const totalSeconds = Math.floor(typeof seconds === 'string' ? parseFloat(seconds) : seconds)

  const h = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
  const m = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
  const s = String(totalSeconds % 60).padStart(2, '0')

  return `${h}:${m}:${s}`
}

// 格式化时间显示
const formatTime = (timeValue) => {
  if (!timeValue) return ''

  // 如果是数字（秒数），转换为时间格式
  if (typeof timeValue === 'number' || !isNaN(parseFloat(timeValue))) {
    return secondsToTimeString(timeValue)
  }

  // 如果是字符串类型，直接处理
  if (typeof timeValue === 'string') {
    // 如果是 HH:mm:ss 格式，只显示 HH:mm
    if (timeValue.includes(':')) {
      return timeValue.substring(0, 5)
    }
    // 如果是秒数字符串，转换为时间格式
    return secondsToTimeString(parseFloat(timeValue))
  }

  // 如果是 Date 对象
  if (timeValue instanceof Date) {
    const hours = timeValue.getHours().toString().padStart(2, '0')
    const minutes = timeValue.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  }

  // 如果是 moment 或类似的对象，有 format 方法
  if (typeof timeValue === 'object' && typeof timeValue.format === 'function') {
    return timeValue.format('HH:mm')
  }

  // 其他情况转换为字符串再处理
  return String(timeValue).substring(0, 5)
}

// 获取教练ID
const getCoachId = async () => {
  try {
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return null
    }

    const response = await requestUtil.get(`/coach/msg/userId/${userId}`)
    return response.data.data.coach_id
  } catch (error) {
    console.error('获取教练信息失败:', error)
    ElMessage.error('获取教练信息失败: ' + (error.message || '未知错误'))
    return null
  }
}

// 获取排班列表
const fetchSchedules = async () => {
  loading.value = true
  try {
    const coachId = await getCoachId()
    if (!coachId) return

    const response = await requestUtil.get(`/schedule/msg/${coachId}`)

    // 处理时间格式转换
    let schedulesData = response.data.data || []

    // 将秒数转换为 HH:mm:ss 格式，并添加星期文本
    schedules.value = schedulesData.map(schedule => {
      const dayItem = weekdays.find(d => d.value === schedule.day_of_week)
      return {
        ...schedule,
        start_time: schedule.start_time,
        end_time: schedule.end_time,
        day_text: dayItem ? dayItem.label : schedule.day_of_week
      }
    })
  } catch (error) {
    console.error('获取排班信息失败:', error)
    ElMessage.error('获取排班信息失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 查看排班详情
const viewScheduleDetail = (schedule) => {
  const dayItem = weekdays.find(d => d.value === schedule.day_of_week)
  selectedSchedule.value = {
    ...schedule,
    day_text: dayItem ? dayItem.label : schedule.day_of_week
  }
  detailDialogVisible.value = true
}

// 工具函数：获取星期显示名称
const getDayOfWeek = (dayNumber) => {
  const day = weekdays.find(d => d.value === dayNumber)
  return day ? day.label : dayNumber
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSchedules()
})
</script>

<style scoped>
.schedule-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.feedback-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.feedback-table {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  /* 确保表格高度足够 */
  min-height: 300px;
}

.feedback-table :deep(.el-table__cell) {
  padding: 16px 0;
  text-align: center;
  /* 增加单元格高度 */
  height: 60px;
  line-height: 1.5;
}

.feedback-table :deep(.el-table th) {
  font-weight: 600;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 0;
}

.feedback-table :deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

.operation-button {
  margin: 0 2px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 减少 ResizeObserver 错误的样式 */
:deep(.el-table) {
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .schedule-management {
    padding: 10px;
  }

  .feedback-table :deep(.el-table__cell) {
    padding: 12px 0;
    height: 50px;
  }

  .operation-button {
    margin: 2px 0;
  }
}
</style>
